package com.qs.eggs.user;

import android.app.Activity;
import android.content.Intent;

import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.qs.eggs.Constants;
import com.qs.eggs.R;
import com.qs.eggs.account.LoginActivity;
import com.qs.eggs.base.activity.BaseActivity;
import com.qs.eggs.loader.PicassoImageLoader;
import com.qs.eggs.view.activity.UpUserInfoActivity;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class UserInfoActivity extends BaseActivity implements View.OnClickListener{
    private Toolbar back;
    private RelativeLayout touxiang;
    private TextView zhanghu,name,phone,jifen,changepwd;
    private Button exit;
    private String custname,xingming,imageUrl,number,score;
    private SimpleDraweeView draweeView;
    public static Activity instance;

    @Override
    protected int getContentView() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        instance=this;
        initView();
    }

    private void initView(){
        touxiang=(RelativeLayout)findViewById(R.id.rl_touxiang);
        draweeView=(SimpleDraweeView)findViewById(R.id.touxiang);
        zhanghu=(TextView)findViewById(R.id.zhanghu);
        name=(TextView)findViewById(R.id.name);
        phone=(TextView)findViewById(R.id.phone);
        jifen=(TextView)findViewById(R.id.jifen);
        changepwd=(TextView)findViewById(R.id.changepwd);
        exit=(Button)findViewById(R.id.exit);
        back=(Toolbar)findViewById(R.id.toolbar);
        touxiang.setOnClickListener(this);
        zhanghu.setOnClickListener(this);
        name.setOnClickListener(this);
        phone.setOnClickListener(this);
        jifen.setOnClickListener(this);
        changepwd.setOnClickListener(this);
        exit.setOnClickListener(this);
        back.setOnClickListener(this);
        getPersonalInfo();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar:
                UserInfoActivity.this.finish();
                break;
            case R.id.rl_touxiang:
                ImagePicker imagePicker = ImagePicker.getInstance();
                imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
                imagePicker.setShowCamera(true);  //显示拍照按钮
                imagePicker.setCrop(true);        //允许裁剪（单选才有效）
                imagePicker.setSaveRectangle(true); //是否按矩形区域保存
                imagePicker.setSelectLimit(1);    //选中数量限制
                imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
                imagePicker.setFocusWidth(500);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
                imagePicker.setFocusHeight(500);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
                imagePicker.setOutPutX(80);//保存文件的宽度。单位像素
                imagePicker.setOutPutY(80);//保存文件的高度。单位像素

                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, 1001);
                break;
            case R.id.zhanghu:
                Intent intent4=new Intent(UserInfoActivity.this, UpUserInfoActivity.class);
                intent4.putExtra("flag","4");
                startActivity(intent4);
                break;
            case R.id.name:
                Intent intent1=new Intent(UserInfoActivity.this, UpUserInfoActivity.class);
                intent1.putExtra("flag","1");
                startActivity(intent1);
                break;
            case R.id.phone:
                Intent intent2=new Intent(UserInfoActivity.this, UpUserInfoActivity.class);
                intent2.putExtra("flag","2");
                startActivity(intent2);
                break;
            case R.id.changepwd:
                Intent intent3=new Intent(UserInfoActivity.this, UpUserInfoActivity.class);
                intent3.putExtra("flag","3");
                startActivity(intent3);
                break;
            case R.id.exit:
                outLogin();
                break;
        }
    }
    //获取用户信息
    private void getPersonalInfo(){
        OkGo.post(Constants.URL_BASE+"personal?action=getPersonalInfo")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("个人信息=="+s);
                        try {
                            JSONArray jsonArray = new JSONArray(s);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                custname=jsonArray.getJSONObject(i).getString("accountname");
                                xingming=jsonArray.getJSONObject(i).getString("name");
                                number=jsonArray.getJSONObject(i).getString("phone");
                                score=jsonArray.getJSONObject(i).getString("score");
                                imageUrl= Constants.URL_BASE+jsonArray.getJSONObject(i).getString("folder")+"/"
                                        +jsonArray.getJSONObject(i).getString("autoname");
                                draweeView.setImageURI(imageUrl);
                                zhanghu.setText(custname);
                                name.setText(xingming);
                                phone.setText(number);
                                jifen.setText(score);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    //退出登录
    private void outLogin(){
        OkGo.post(Constants.URL_BASE+"mallLogin?action=exiteMallLogin ")
                .execute(new StringCallback(){
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("退出登录=="+s);
                        if (s.equals("\"true\"")){
                            UserInfoActivity.this.finish();
                            Intent intent=new Intent(UserInfoActivity.this, LoginActivity.class);
                            startActivity(intent);
                        }
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 1001) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem image=images.get(0);
                uploadFile(image);
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }


    //上传
    public void uploadFile(final ImageItem image) {
        final List<File> files=new ArrayList<>();
        File file=new File(image.path);
        Luban.get(this)
                .load(file)                     //传人要压缩的图片
                .setCompressListener(new OnCompressListener() { //设置回调

                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onSuccess(File file) {
                        files.add(file);
                        //作为文件名
                        long time=System.currentTimeMillis();
                        OkGo.post(Constants.URL_BASE+"personal?action=uploadCustomerImage")
                                .addFileParams(time+"",files)
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        System.out.print("上传头像=="+s);
                                        if (s.equals("\"true\"")){
                                            //可能导致内存溢出
                                            getPersonalInfo();
                                            Toast.makeText(UserInfoActivity.this,"头像上传成功",Toast.LENGTH_SHORT).show();
                                        }else{
                                            Toast.makeText(UserInfoActivity.this,"头像上传失败",Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onError(Call call, Response response, Exception e) {
                                        super.onError(call, response, e);
                                    }
                                });
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();

    }

}
